package com.cloud.base.thread.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class CASMain {
    //unsafe  单例的  所以要反射获取对象
    public static void main(String[] args) {
        CASMain casMain = new CASMain();
        Unsafe unsafe = casMain.getUnsafe();
        System.out.println(unsafe.compareAndSwapInt(casMain, 0, 0, 1));
        System.out.println(casMain.getUnsafeConst().compareAndSwapInt(casMain, 0, 1, 1));
    }

    private static Unsafe getUnsafe() {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            return (Unsafe) field.get(null);
        } catch (Exception e) {
            return null;
        }
    }

    private static Unsafe getUnsafeConst() {
        try {
            Class<Unsafe> aClass = (Class<Unsafe>) Class.forName("sun.misc.Unsafe");
            Constructor<Unsafe> constructor = aClass.getDeclaredConstructor();
            constructor.setAccessible(true);
            Unsafe unsafe = constructor.newInstance();
            return unsafe;
        } catch (Exception e) {
            return null;
        }
    }
}
